package com.gz.university.crm.web.action;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.BeanUtils;

import com.gz.university.crm.annotation.Limit;
import com.gz.university.crm.bean.DataType;
import com.gz.university.crm.bean.DatePatternUtils;
import com.gz.university.crm.bean.Encrypt;
import com.gz.university.crm.bean.SessionUtils;
import com.gz.university.crm.entity.SysRole;
import com.gz.university.crm.entity.SysUser;
import com.gz.university.crm.entity.SysUserGroup;
import com.gz.university.crm.form.SysUserForm;
import com.gz.university.crm.service.ISysRoleService;
import com.gz.university.crm.service.ISysUserGroupService;
import com.gz.university.crm.service.ISysUserService;
import com.opensymphony.xwork2.ModelDriven;

@SuppressWarnings("serial")
@ParentPackage("basePackage")
@Namespace("/")
@Action(value = "sysUserAction")
@Results({
		@Result(name = "list", location = "/WEB-INF/page/sys/user/list.jsp"),
		@Result(name = "add", location = "/WEB-INF/page/sys/user/add.jsp"),
		@Result(name = "main", location = "/WEB-INF/page/menu/main.jsp"),
		@Result(name = "login", location = "/WEB-INF/page/login.jsp"),
		@Result(name = "edit", location = "/WEB-INF/page/sys/user/edit.jsp"),
		@Result(name = "toListAction", type = "redirect", location = "sysUserAction!list.action") })
public class SysUserAction extends BaseAction implements
		ModelDriven<SysUserForm> {
	private SysUserForm sysUserForm = new SysUserForm();
	private ISysUserService sysUserService;
	private ISysRoleService sysRoleService;// 权限
	private ISysUserGroupService sysUserGroupService;// 部门

	public ISysRoleService getSysRoleService() {
		return sysRoleService;
	}

	@Resource(name = ISysRoleService.SERVICE_NAME)
	public void setSysRoleService(ISysRoleService sysRoleService) {
		this.sysRoleService = sysRoleService;
	}

	public ISysUserGroupService getSysUserGroupService() {
		return sysUserGroupService;
	}

	@Resource(name = ISysUserGroupService.SERVICE_NAME)
	public void setSysUserGroupService(ISysUserGroupService sysUserGroupService) {
		this.sysUserGroupService = sysUserGroupService;
	}

	public ISysUserService getSysUserService() {
		return sysUserService;
	}

	@Resource(name = ISysUserService.SERVICE_NAME)
	public void setSysUserService(ISysUserService sysUserService) {
		this.sysUserService = sysUserService;
	}

	/**
	 * 显示用户的查询界面
	 * 
	 * @return
	 */
	@Limit(module="user",privilege="list")
	public String list() {
		// 处理部门的下拉选
		List<SysUserGroup> sysUserGroupSelect = this.sysUserGroupService
				.findAllSysUserGroup();
		this.getRequest()
				.setAttribute("sysUserGroupSelect", sysUserGroupSelect);
		// 条件查询
		List<SysUser> sysUserList = this.sysUserService
				.findSysUserByConditions(sysUserForm);
		this.getRequest().setAttribute("sysUserList", sysUserList);
		return "list";
	}

	/**
	 * 显示用户信息的添加界面
	 * 
	 * @return
	 */
	@Limit(module="user",privilege="add")
	public String add() {
		// 处理权限组的下拉选
		List<SysRole> sysRoleSelect = this.sysRoleService.findAllSysRoles();
		this.getRequest().setAttribute("sysRoleSelect", sysRoleSelect);
		// 处理部门的下拉选
		List<SysUserGroup> sysUserGroupSelect = this.sysUserGroupService
				.findAllSysUserGroup();
		this.getRequest()
				.setAttribute("sysUserGroupSelect", sysUserGroupSelect);
		// 处理创建人修改人创建时间，修改时间
		// 获取当前登录的用户
		SysUser sysUser = SessionUtils.getSysUserFromSesion(this.getRequest());
		if (sysUser == null) {
			return "login";
		}
		// 设置新建人和修改人信息，添加信息是新建人个修改人信息一致
		sysUserForm.setCreator(sysUser.getCnname());
		sysUserForm.setUpdater(sysUser.getCnname());
		String currentTime = DateFormatUtils.format(new Date(),
				"yyyy-MM-dd HH:mm:ss");
		sysUserForm.setCreateTime(currentTime);
		sysUserForm.setUpdateTime(currentTime);
		return "add";
	}
    /**
     * 
     * @return
     */
	@Limit(module="user",privilege="delete")
	public String delete() {
		// 获取IDS
		String[] idStrings = this.getRequest().getParameterValues("ids");
		Integer[] idsIntegers = DataType
				.convertStringArrayToIntegerArray(idStrings);
		if (idsIntegers != null && idsIntegers.length > 0) {
			// 删除
			this.sysUserService.deleteSysUsersByIds(idsIntegers);
			return "toListAction";
		}
		return null;
	}

	/**
	 * 保存新增用户信息
	 * 
	 * @return
	 * @throws ParseException
	 */
	@Limit(module="user",privilege="save")
	public String save() throws ParseException {
		SysUser sysUser = new SysUser();
		BeanUtils.copyProperties(sysUserForm, sysUser, new String[] {
				"sysUserId", "password", "createTime", "updateTime",
				"beginDate", "endDate", "sysRole", "sysUserGroup", "birthday",
				"workDate", "finishSchoolDate" });
		// 权限组
		SysRole sysRole = new SysRole();
		sysRole.setSysRoleId(Integer.parseInt(sysUserForm.getRoleId()));
		sysUser.setSysRole(sysRole);
		// 处理部门
		SysUserGroup sysUserGroup = new SysUserGroup();
		if (StringUtils.isNotBlank(sysUserForm.getGroupId())) {
			sysUserGroup.setSysUserGroupId(Integer.parseInt(sysUserForm
					.getGroupId()));
		}
		sysUser.setSysUserGroup(sysUserGroup);
		DateFormat fmtDate = new SimpleDateFormat("yyyy-MM-dd");
		sysUser.setBeginDate(fmtDate.parse(sysUserForm.getBeginDate()));
		sysUser.setEndDate(fmtDate.parse(sysUserForm.getEndDate()));
		sysUser.setBirthday(fmtDate.parse(sysUserForm.getBirthday()));
		sysUser.setWorkDate(fmtDate.parse(sysUserForm.getWorkDate()));
		sysUser.setFinishSchoolDate(fmtDate.parse(sysUserForm
				.getFinishSchoolDate()));
		DateFormat fmtTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		sysUser.setCreateTime(fmtTime.parse(sysUserForm.getCreateTime()));
		sysUser.setUpdateTime(fmtTime.parse(sysUserForm.getUpdateTime()));
		// 用户密码加密
		sysUser.setPassword(Encrypt.md5(sysUserForm.getPassword()));
		/* 保存当前用户 */
		this.sysUserService.saveSysUser(sysUser);
		return "toListAction";
	}
	public String isLogin() {
		// 处理验证码，判断验证码输入的是否正确
		boolean flag = SessionUtils.isCheckNum(this.getRequest());
		if (!flag) {
			this.addFieldError("checkNum", "验证码输入有误，请重新输入");
			return "login";
		}
		// 判断用户名和密码输入的是否正确
		String name = this.getRequest().getParameter("name");
		String password = Encrypt.md5(this.getRequest()
				.getParameter("password"));
		SysUser sysUser = this.sysUserService.findSysUserByNameAndPassword(
				name, password);
		if (sysUser == null) {
			this.addFieldError("name", "用户名或者密码错误，请检查！");
			return "login";
		}
		// 登录成功后将sysUser放到session中
		SessionUtils.setSysUserToSession(this.getRequest(), sysUser);
		// 处理cookies
		try {
			addCookie(name, this.getRequest().getParameter("password"),
					this.getResponse(), this.getRequest());
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "main";
	}

	private void addCookie(String name, String password,
			HttpServletResponse response, HttpServletRequest request)
			throws UnsupportedEncodingException {
		// TODO Auto-generated method stub
		if (StringUtils.isNotBlank(name) && StringUtils.isNotBlank(password)) {
			// 创建cookie
			Cookie nameCookie = new Cookie("name", URLEncoder.encode(name,
					"utf-8"));
			Cookie pswCookie = new Cookie("psw", password);
			// 设置cookie的父路径
			nameCookie.setPath(request.getContextPath());
			pswCookie.setPath(request.getContextPath());
			/* String pathString=request.getContextPath();/crm */
			String rememberMe = this.getRequest().getParameter("rememberMe");
			if (rememberMe == null) {// 不保存cookie,填写cookie保存的时间以秒为
				nameCookie.setMaxAge(0);
				pswCookie.setMaxAge(0);
			} else {// 保存cookie
				nameCookie.setMaxAge(7 * 24 * 60 * 60);
				pswCookie.setMaxAge(7 * 24 * 60 * 60);
			}
			// 加入cookie到相应的头
			response.addCookie(nameCookie);
			response.addCookie(pswCookie);
		}
	}

	/**
	 * 启用
	 * 
	 * @return
	 */
	@Limit(module="user",privilege="enable")
	public String enable() {
		String[] idStrings = this.getRequest().getParameterValues("ids");
		Integer[] ids = DataType.convertStringArrayToIntegerArray(idStrings);
		if (ids != null && ids.length > 0) {
			// 启用
			this.sysUserService.updateSysUserStatus(ids);
			return "toListAction";
		}
		return null;
	}

	/**
	 * 停用用户
	 * 
	 * @return
	 */
	@Limit(module="user",privilege="disable")
	public String disable() {
		String[] idStrings = this.getRequest().getParameterValues("ids");
		Integer[] ids = DataType.convertStringArrayToIntegerArray(idStrings);
		if (ids != null && ids.length > 0) {
			this.sysUserService.updateStatusDisable(ids);
			return "toListAction";
		}
		return null;
	}

	/**
	 * 
	 * @return
	 */
	@Limit(module="user",privilege="edit")
	public String edit() {
		// 获取sysUserId
		String sid = this.getRequest().getParameter("sysUserId");
		if (StringUtils.isNotBlank(sid)) {
			Integer id = Integer.parseInt(sid.trim());
			SysUser sysUser = this.sysUserService.findSysUserById(id);
			BeanUtils.copyProperties(sysUser, sysUserForm, new String[] {
					"createTime", "updateTime", "beginDate", "endDate",
					"birthday", "workDate", "finishSchoolDate" });
			sysUserForm.setCreateTime(DateFormatUtils.format(
					sysUser.getCreateTime(), DatePatternUtils.TIME_PATTERN));
			sysUserForm.setUpdateTime(DateFormatUtils.format(
					sysUser.getUpdateTime(), DatePatternUtils.TIME_PATTERN));
			sysUserForm.setBeginDate(DateFormatUtils.format(
					sysUser.getBeginDate(), DatePatternUtils.DATE_PATTERN));
			sysUserForm.setEndDate(DateFormatUtils.format(sysUser.getEndDate(),
					DatePatternUtils.DATE_PATTERN));
			sysUserForm.setBirthday(DateFormatUtils.format(
					sysUser.getBirthday(), DatePatternUtils.DATE_PATTERN));
			sysUserForm.setWorkDate(DateFormatUtils.format(
					sysUser.getWorkDate(), DatePatternUtils.DATE_PATTERN));
			sysUserForm.setFinishSchoolDate(DateFormatUtils.format(
					sysUser.getFinishSchoolDate(),
					DatePatternUtils.DATE_PATTERN));
			// 处理部门的下拉选
			List<SysUserGroup> sysUserGroupSelect = this.sysUserGroupService
					.findAllSysUserGroup();
			this.getRequest().setAttribute("sysUserGroupSelect",
					sysUserGroupSelect);
			// 处理所属部门
			List<SysRole> sysRoleSelect = this.sysRoleService.findAllSysRoles();
			this.getRequest().setAttribute("sysRoleSelect", sysRoleSelect);
			// 处理权限组的下拉选的回现
			if (sysUser.getSysRole() != null) {
				sysUserForm.setRoleId(sysUser.getSysRole().getSysRoleId()
						.toString());
			}
			// 处理部门的回现
			if (sysUser.getSysUserGroup() != null) {
				sysUserForm.setGroupId(sysUser.getSysUserGroup()
						.getSysUserGroupId().toString());
			}
			/*
			 * // 条件查询 List<SysUser> sysUserList = this.sysUserService
			 * .findSysUserByConditions(sysUserForm);
			 * this.getRequest().setAttribute("sysUserList", sysUserList);
			 */
			return "edit";
		}
		return null;
	}

	/**
	 * 跟新用户信息
	 * 
	 * @return
	 * @throws ParseException 
	 */
	@Limit(module="user",privilege="update")
	public String update() throws ParseException {
		SysUser sysUser = new SysUser();
		BeanUtils.copyProperties(sysUserForm, sysUser, new String[] {
				"createTime", "updateTime", "beginDate", "endDate", "sysRole",
				"sysUserGroup", "birthday", "workDate", "finishSchoolDate" });
		// 权限组
		SysRole sysRole = new SysRole();
		sysRole.setSysRoleId(Integer.parseInt(sysUserForm.getRoleId()));
		sysUser.setSysRole(sysRole);
		// 处理部门
		SysUserGroup sysUserGroup = new SysUserGroup();
		if (StringUtils.isNotBlank(sysUserForm.getGroupId())) {
			sysUserGroup.setSysUserGroupId(Integer.parseInt(sysUserForm
					.getGroupId()));
		}
		sysUser.setSysUserGroup(sysUserGroup);
		DateFormat fmtDate = new SimpleDateFormat(DatePatternUtils.DATE_PATTERN);
		sysUser.setBeginDate(fmtDate.parse(sysUserForm.getBeginDate()));
		sysUser.setEndDate(fmtDate.parse(sysUserForm.getEndDate()));
		sysUser.setBirthday(fmtDate.parse(sysUserForm.getBirthday()));
		sysUser.setWorkDate(fmtDate.parse(sysUserForm.getWorkDate()));
		sysUser.setFinishSchoolDate(fmtDate.parse(sysUserForm
				.getFinishSchoolDate()));
		DateFormat fmtTime = new SimpleDateFormat(DatePatternUtils.TIME_PATTERN);
		sysUser.setCreateTime(fmtTime.parse(sysUserForm.getCreateTime()));
		sysUser.setUpdateTime(fmtTime.parse(sysUserForm.getUpdateTime()));
		//获取当前登录用户
		SysUser currentSysUser=SessionUtils.getSysUserFromSesion(this.getRequest());
		if (currentSysUser==null) {
			return "login";
		}
		sysUser.setUpdater(currentSysUser.getCnname());
		sysUser.setUpdateTime(new Date());
		/* 保存当前用户 */
		this.sysUserService.updateSysUser(sysUser);
		return "toListAction";
	}

	@Override
	public SysUserForm getModel() {
		// TODO Auto-generated method stub
		return sysUserForm;
	}

}
